import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP ;
    private int serverPort;

    //客户端要启动，需要知道服务器在哪里！
    public UdpEchoClient(String serverIP, int serverPort)throws SocketException {
        //对于客户端来说，系统会自动分配一个空闲的端口
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    //通过这个客户端可以多次和服务器进行交互
    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        while(true){
            // 1. 先读取用户的请求
            System.out.print("->");
            String request = sc.nextLine();
            // 2. 把字符串构造出 UDF 的packet，并进行发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            socket.send(requestPacket);
            // 3. 客户端尝试读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4090], 4090);
            socket.receive(responsePacket);
            //把响应的数据转换成 String 显示出来
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("请求：%s, 响应：%s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException{
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",1000);
        udpEchoClient.start();
    }
}
